<?php
/**
 * Created by PhpStorm.
 * User: yangfan
 * Date: 2019/11/22
 * Time: 5:53 PM
 */

namespace App\Services;

use App\Entity\DistributorEntity;
use App\Entity\TransactionRecordEntity;
use App\Entity\UserEntity;
use App\Inc\OrderInc;
use App\Models\Distributor;
use App\Models\TransactionRecord;
use App\Services\api\IUserBalanceService;
use Illuminate\Support\Facades\DB;

/**
 * 用户余额服务
 * Class UserBalanceService
 * @package App\Services
 */
class UserBalanceService implements IUserBalanceService
{
    /**
     * @var UserEntity
     */
    private $user;

    /**
     * @var DistributorEntity
     */
    private $distributorEntity;

    public function __construct(UserEntity $user)
    {
        $this->user = $user;
        $distributor = Distributor::where('dis_id', '=', $user->getUserId())->first();

        if ($distributor instanceof Distributor) {
            $this->distributorEntity = new DistributorEntity($distributor);
        } else {
            // 为用户新建一个账户
            $distributorEntity = DistributorEntity::getNewInstance();
            $distributorEntity->setDisId($user->getUserId());
            $distributorEntity->setDisName($user->getName());
            $distributorEntity->setPhone($user->getPhone());
            $distributorEntity->save();

            $this->distributorEntity = $distributorEntity;
        }
    }

    /**
     * @return DistributorEntity
     */
    public function getDistributorEntity()
    {
        return $this->distributorEntity;
    }

    /**
     * @return TransactionRecordEntity[]
     */
    public function getTransactionRecordEntityList()
    {
        $arr = [];

        $records = TransactionRecord::where('dis_id', '=', $this->user->getUserId())
            ->orderBy('id', 'desc')
            ->get();

        foreach ($records as $record) {
            $arr[] = new TransactionRecordEntity($record);
        }

        return $arr;
    }

    /**
     * 用户的可用余额
     * @return int
     */
    public function getUseAbleAmount()
    {
        return $this->distributorEntity->getBalance();
    }

    /**
     * 用户被冻结的余额
     * @return int
     */
    public function getFrozenAmount()
    {
        return $this->distributorEntity->getFreezeBalance();
    }

    /**
     * 用户使用余额，默认一次用完
     * @param $amount
     * @return int
     */
    public function use($amount)
    {
        $remainAmount = max(0, $this->getUseAbleAmount() - $amount);

        DB::beginTransaction();

        // 1. 修改余额表
        $this->distributorEntity->setBalance($remainAmount);
        $this->distributorEntity->save();

        // 2. 记录余额使用记录
        $record = TransactionRecordEntity::getNewInstance();
        $record->setDisId($this->user->getUserId());
        $record->setMoney(-1 * $amount);
        $record->setType(OrderInc::TRANSACTION_RECORD_TYPE_余额抵扣);
        $record->setCreatedAt(date('Y-m-d H:i:s', time()));
        $record->save();

        DB::commit();

        return $record->getId();
    }
}
